import Vue from 'vue';
import iView from 'iview';
import VueRouter from 'vue-router';
import VueResource from 'vue-resource';
import Routers from './router';
import Util from './libs/util';
import App from './app.vue';
import axios from 'axios';
import Vuex from 'vuex';
import format from './util/Date';
import barcode from './util/jquery-barcode-2.0.1';
import 'iview/dist/styles/iview.css';
import './styles/iconfont.css';
import './styles/common.css';
import * as filters from './util/filter';

//全局配置
//应用于所有请求
axios.defaults.baseURL = "http://172.16.7.78:8750/";
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
axios.defaults.headers.put["Content-Type"] = "application/json";
//axios.defaults.timeout = 20000;//超时时间
//axios.defaults.headers.common['Authorization'] = "Bearer "+localStorage.getItem('token');
//拦截请求与响应,在 then 或 catch 之前拦截处理
// 请求拦截
// http request 拦截器
axios.interceptors.request.use(
    config => {
        if (localStorage.getItem('token')) {
            config.headers.Authorization = "Bearer "+localStorage.getItem('token');
        }
        return config;
    },
    err => {
        iView.Message.error('错误的传参!');
        return Promise.reject(err);
    });

// http response 拦截器
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 401 清除token信息并跳转到登录页面
                    localStorage.removeItem('token');
                    if(router.currentRoute.fullPath == "/login"){
                        router.replace({
                            path: '/login'
                        })
                    }else{
                        iView.Message.destroy();
                        router.replace({
                            path: '/login',
                            query: {redirect: router.currentRoute.fullPath}
                        })
                    }
                    break;
                case 500:
                    iView.LoadingBar.error();
                    iView.Message.error(error.response.data);
                    break;
                case 501:
                    iView.LoadingBar.error();
                    iView.Message.error('服务器不具备完成请求的功能!');
                    break;
                case 502:
                    iView.LoadingBar.error();
                    iView.Message.error('服务器遇到错误，无法完成请求!');
                    break;
                case 503:
                    iView.LoadingBar.error();
                    iView.Message.error('服务器目前无法使用（由于超载或停机维护）!');
                    break;
                case 504:
                    iView.LoadingBar.error();
                    iView.Message.error('服务器遇到错误，无法完成请求!');
                    break;
                case 505:
                    iView.LoadingBar.error();
                    iView.Message.error('服务器遇到错误，无法完成请求!');
                    break;
            }
            return Promise.reject(error.response.data)
        }else{
            iView.LoadingBar.error();
            iView.Message.error('服务器连接超时，请联系管理员!');
            return Promise.reject("服务器崩溃！")
        }

    });
Object.keys(filters).forEach(k => Vue.filter(k, filters[k])) //注册过滤器

Vue.use(VueRouter);
Vue.use(VueResource);
Vue.use(iView);
Vue.use(Vuex);

// 路由配置
const RouterConfig = {
    mode: 'history',
    routes: Routers
};
const router = new VueRouter(RouterConfig);
const store = new Vuex.Store({
    state: {
        url:'http://172.16.7.78:8750',
        width: window.innerWidth-235,
        loadModal:false
    }
});
router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
        if (localStorage.getItem('token')) {  // 通过获取当前的token是否存在
            iView.LoadingBar.start();
            Util.title(to.meta.title);
            localStorage.setItem("activeName",to.fullPath);
            next();
        }
        else {
            next({
                path: '/login',
                query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
            })
        }
    }
    else {
        iView.LoadingBar.start();
        Util.title(to.meta.title);
        next();
    }
});
router.afterEach((to, from, next) => {
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
});
// 注册一个全局自定义指令 v-focus
Vue.directive('focus', {
    // 当绑定元素插入到 DOM 中。
    inserted: function (el) {
        // 聚焦元素
        el.focus()
    }
});
//自定义指令  拖拽
Vue.directive('drag',//自定义指令JS
    {bind:function (el) {
        let oDiv = el;   //当前元素
        let self = this;  //上下文
        oDiv.onmousedown = function (e) {
            //鼠标按下，计算当前元素距离可视区的距离
            let disX = e.clientX - oDiv.offsetLeft;
            let disY = e.clientY - oDiv.offsetTop;
            document.onmousemove = function (e) {
                //通过事件委托，计算移动的距离
                let l = e.clientX - disX;
                let t = e.clientY - disY;
                //移动当前元素
                el.parentNode.parentNode.parentNode.style.left = l + 'px';
                el.parentNode.parentNode.parentNode.style.top = t + 'px';
            };
            document.onmouseup = function (e) {
                document.onmousemove = null;
                document.onmouseup = null;
            };
        };
    }
    }
);
new Vue({
    el: '#app',
    router: router,
    axios,
    format,
    barcode,
    store: store,
    render: h => h(App)
});
